package controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import service.UserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "用户管理", description = "系统用户相关接口")
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询所有用户", notes = "获取系统所有用户信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功返回用户列表", response = User.class, responseContainer = "List")
    })
    @GetMapping("/findAll")
    public ResponseEntity<List<User>> findAll() {
        return ResponseEntity.ok(userService.findAll());
    }

    @ApiOperation(value = "根据ID查询用户", notes = "通过user_id获取单个用户信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功返回用户", response = User.class),
            @ApiResponse(code = 404, message = "未找到对应用户")
    })
    @GetMapping("/findById/{userId}")
    public ResponseEntity<User> findById(@PathVariable Integer userId) {
        User user = userService.findById(userId);
        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
    }

    @ApiOperation(value = "用户登录", notes = "用户账号密码登录")
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功", response = Map.class),
            @ApiResponse(code = 401, message = "用户名或密码错误"),
            @ApiResponse(code = 404, message = "用户不存在")
    })
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginInfo) {
        String userName = loginInfo.get("userName");
        String password = loginInfo.get("password");

        if (userName == null || password == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                    buildResultMap(false, "用户名和密码不能为空")
            );
        }

        User user1 = userService.findByUserName(userName);
        if (user1 == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(
                    buildResultMap(false, "用户不存在")
            );
        }

        if (!password.equals(user1.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(
                    buildResultMap(false, "密码错误")
            );
        }

        // 登录成功，更新登录时间和次数
        userService.updateLoginInfo(user1.getUserId());

        Map<String, Object> result = buildResultMap(true, "登录成功");
        result.put("userInfo", user1);
        return ResponseEntity.ok(result);
    }

    @ApiOperation(value = "新增用户", notes = "创建一个新的系统用户")
    @ApiResponses({
            @ApiResponse(code = 201, message = "用户创建成功"),
            @ApiResponse(code = 400, message = "无效的用户数据")
    })
    @PostMapping("/addUser")
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.findByUserName(user.getUserName()) != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(
                    buildResultMap(false, "用户名已存在")
            );
        }

        try {
            userService.addUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(
                    buildResultMap(true, "用户创建成功")
            );
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                    buildResultMap(false, "用户创建失败：" + e.getMessage())
            );
        }
    }

    @ApiOperation(value = "用户注册", notes = "用户注册新账号")
    @ApiResponses({
            @ApiResponse(code = 201, message = "注册成功"),
            @ApiResponse(code = 400, message = "无效的注册数据"),
            @ApiResponse(code = 409, message = "用户名已存在")
    })
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> registerInfo) {
        String userName = registerInfo.get("userName");
        String phone = registerInfo.get("phone");
        String password = registerInfo.get("password");
        String userRole = registerInfo.get("userRole");

        // 参数验证
        if (userName == null || password == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                    buildResultMap(false, "用户名和密码不能为空")
            );
        }

        // 检查用户名是否已存在
        if (userService.findByUserName(userName) != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(
                    buildResultMap(false, "用户名已存在")
            );
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUserName(userName);
        newUser.setTelephone(phone);
        newUser.setPassword(password);
        // 设置用户角色，如果没有提供则默认为"用户"
        newUser.setUserRole(userRole != null ? userRole : "用户");

        try {
            userService.addUser(newUser);
            return ResponseEntity.status(HttpStatus.CREATED).body(
                    buildResultMap(true, "注册成功")
            );
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                    buildResultMap(false, "注册失败：" + e.getMessage())
            );
        }
    }

    @ApiOperation(value = "更新用户信息", notes = "根据用户ID更新信息（不包括密码）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "用户信息更新成功"),
            @ApiResponse(code = 404, message = "未找到对应用户")
    })
    @PostMapping("/updateUserInfo")
    public ResponseEntity<Void> updateUserInfo(@RequestBody User user) {
        int success = userService.updateUserInfo(user);
        return success > 0 ?
                ResponseEntity.ok().build() :
                ResponseEntity.notFound().build();
    }

    @ApiOperation(value = "修改密码", notes = "用户自己修改密码，需要原密码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "密码修改成功"),
            @ApiResponse(code = 404, message = "未找到对应用户"),
            @ApiResponse(code = 403, message = "原密码错误")
    })
    @PostMapping("/updatePassword")
    public ResponseEntity<Map<String, Object>> updatePassword(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        String oldPassword = (String) params.get("oldPassword");
        String newPassword = (String) params.get("newPassword");

        if (userId == null || oldPassword == null || newPassword == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                    buildResultMap(false, "参数不完整")
            );
        }

        User user = userService.findById(userId);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
                    buildResultMap(false, "用户不存在")
            );
        }

        if (!oldPassword.equals(user.getPassword())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
                    buildResultMap(false, "原密码错误")
            );
        }

        int success = userService.updatePassword(userId, newPassword);
        return success > 0 ?
                ResponseEntity.ok(buildResultMap(true, "密码修改成功")) :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                        buildResultMap(false, "密码修改失败")
                );
    }

    @ApiOperation(value = "重置密码", notes = "管理员重置用户密码，无需原密码，统一设置为123456")
    @ApiResponses({
            @ApiResponse(code = 200, message = "密码重置成功"),
            @ApiResponse(code = 404, message = "未找到对应用户"),
            @ApiResponse(code = 400, message = "参数不完整")
    })
    @PostMapping("/resetPassword")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");

        // 检查参数
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                    buildResultMap(false, "用户ID不能为空")
            );
        }

        User user = userService.findById(userId);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
                    buildResultMap(false, "用户不存在")
            );
        }

        // 新密码固定为123456
        String newPassword = "123456";

        int success = userService.updatePassword(userId, newPassword);
        return success > 0 ?
                ResponseEntity.ok(buildResultMap(true, "密码已重置为123456")) :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                        buildResultMap(false, "密码重置失败")
                );
    }

    @ApiOperation(value = "删除用户", notes = "根据用户ID删除记录")
    @ApiResponses({
            @ApiResponse(code = 200, message = "用户删除成功"),
            @ApiResponse(code = 404, message = "未找到对应用户")
    })
    @DeleteMapping("/deleteUser/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer userId) {
        int success = userService.deleteUser(userId);
        return success > 0 ?
                ResponseEntity.ok().build() :
                ResponseEntity.notFound().build();
    }

    // 构建返回结果Map
    private Map<String, Object> buildResultMap(Boolean success, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", success);
        map.put("message", message);
        return map;
    }
}
